package com.bunnyrabbit2.bunnybf3;

import java.util.Date;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.bunnyrabbit2.bunnybf3.helpers.MyApp;
import com.bunnyrabbit2.bunnybf3.helpers.StringHelper;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenedListener;
import com.slidingmenu.lib.app.SlidingActivity;

public abstract class FamiliarActivity extends SlidingActivity {
	
	protected FamiliarActivity me;
	protected Context mCtx;
	protected SharedPreferences preferences;
	
	private PackageInfo pInfo;
	
	private static final int ABOUT_DIALOG = 100;
	private static final int CHANGELOG_DIALOG = 101;
	private static final int DONATE_DIALOG = 102;
	
	private Class<?>	pendingClass = null;
	private int	pendingDialog = -1;
	
	// create some sort of database for the weapon/vehicle stats. Maybe use an API for this
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
		}
		catch (NameNotFoundException e) {
			pInfo = null;
		}
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayHomeAsUpEnabled(true);
		
		getSlidingMenu().setBehindOffsetRes(R.dimen.actionbar_home_width);
		getSlidingMenu().setBehindScrollScale(0.0f);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		setBehindContentView(R.layout.sliding_menu);
		
		me = this;
		mCtx = this;
		
		getSupportActionBar().setDisplayShowTitleEnabled(false);

		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		
		boolean autoUpdate = preferences.getBoolean("autoupdate", true);
		if(autoUpdate)
		{
			//Only update if it hasn't been updated recently
			long curTime = new Date().getTime();
			int updatefrequency = Integer.valueOf(preferences.getString("updatefrequency", "3"));
			int lastLegalityUpdate = preferences.getInt("lastLegalityUpdate", 0);
			// days to ms
			if (((curTime / 1000) - lastLegalityUpdate) > (updatefrequency * 24 * 60 * 60)) {
				// If we should be updating, check to see if we already are
				MyApp appState = (MyApp) getApplicationContext();
				boolean update;
				synchronized (this) {
					if (!appState.isUpdating()) {
						appState.setUpdating(true);
						appState.setUpdatingActivity(this);
						update = true;
					}
					else {
						update = false;
						if (appState.getUpdatingActivity() != this) {
							// finish();
						}
					}
				}

				if (update) {
					// do the updating thing
				}
			}
		}
		
		// setup database helper.
		
		TextView player = (TextView)findViewById(R.id.player);
		TextView weapons = (TextView)findViewById(R.id.weapons);
		TextView vehicles = (TextView)findViewById(R.id.vehicles);
		TextView assignments = (TextView)findViewById(R.id.assignments);
		TextView achievements = (TextView)findViewById(R.id.achievements);
		TextView server = (TextView)findViewById(R.id.server);
		TextView maps = (TextView)findViewById(R.id.maps);
		
		TextView preferencesButton = (TextView)findViewById(R.id.preferences);
		TextView donate = (TextView)findViewById(R.id.donate);
		TextView whatsNew = (TextView)findViewById(R.id.whatsnew);
		TextView about = (TextView)findViewById(R.id.aboutapp);
		
		getSlidingMenu().setOnClosedListener(new OnClosedListener(){
			@Override
			public void onClosed() {
				if(pendingClass != null){
					Intent i = new Intent(mCtx, pendingClass);
					startActivity(i);
					pendingClass = null;
				}
				else if(pendingDialog != -1){
					showDialog(pendingDialog);
					pendingDialog = -1;
				}	
			}});

		getSlidingMenu().setOnOpenedListener(new OnOpenedListener(){
			@Override
			public void onOpened() {
				// Close the keyboard if the slidingMenu is opened
				try{
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	        imm.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0);
				}
				catch(NullPointerException e){
					// eat it
				}
			}});
		
		/*
		player.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(PlayerActivity.class);
			}
		});
		*/
		
		weapons.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(WeaponsActivity.class);
			}
		});
		
		/*
		vehicles.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(VehiclesActivity.class);
			}
		});
		
		assignments.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(AssignmentsActivity.class);
			}
		});
		
		server.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(ServerActivity.class);
			}
		});
		
		maps.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(MapsActivity.class);
			}
		});
		*/
		
		preferencesButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingActivityLauncher(PreferencesActivity.class);
			}
		});
				
		donate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingDialogLauncher(DONATE_DIALOG);
			}
		});
		
		whatsNew.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingDialogLauncher(CHANGELOG_DIALOG);
			}
		});
		
		about.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				slidingDialogLauncher(ABOUT_DIALOG);
			}
		});
		
	}
	
	protected void slidingActivityLauncher(final Class<?> class1) {
		pendingClass = class1;
		showAbove();
	}
	
	protected void slidingDialogLauncher(final int id) {
		pendingDialog = id;
		showAbove();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Close any database thing that's open
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		showAbove(); // always close the sliding menu when returning to this activity
		MyApp appState = ((MyApp) getApplicationContext());
		String classname = this.getClass().getCanonicalName();
		
		// use this to drop out of some activities into menu
	
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				toggle();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		
		switch (id) {
			case DONATE_DIALOG: {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.dialog_donate_title);
				builder.setNeutralButton(R.string.dialog_thanks, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
				
				LayoutInflater inflater = getLayoutInflater();
				View dialoglayout = inflater.inflate(R.layout.dialog_about, (ViewGroup) findViewById(R.id.dialog_layout_root));

				TextView text = (TextView) dialoglayout.findViewById(R.id.aboutfield);
				text.setText(StringHelper.jellyBeanHack(getString(R.string.menu_donate_text)));
				text.setMovementMethod(LinkMovementMethod.getInstance());
				
				text.setTextSize(15);
				
				builder.setView(dialoglayout);
				return builder.create();
			}
			
			case CHANGELOG_DIALOG: {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);

				if (pInfo != null) {
					builder.setTitle(R.string.dialog_whats_new_in + pInfo.versionName);
				}
				else {
					builder.setTitle(R.string.dialog_whats_new);
				}

				builder.setNeutralButton(R.string.dialog_enjoy, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

				builder.setMessage(StringHelper.jellyBeanHack(getString(R.string.main_whats_new_text)));
				return builder.create();
			}
			
			case ABOUT_DIALOG: {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);

				// You have to catch the exception because the package stuff is all
				// run-time
				if (pInfo != null) {
					builder.setTitle(R.string.dialog_about + getString(R.string.app_name) + " " + pInfo.versionName);
				}
				else {
					builder.setTitle(R.string.dialog_about + getString(R.string.app_name));
				}

				builder.setNeutralButton(R.string.dialog_thanks, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

				LayoutInflater inflater = getLayoutInflater();
				View dialoglayout = inflater.inflate(R.layout.dialog_about, (ViewGroup) findViewById(R.id.dialog_layout_root));

				TextView text = (TextView) dialoglayout.findViewById(R.id.aboutfield);
				text.setText(StringHelper.jellyBeanHack(getString(R.string.menu_about_text)));
				text.setMovementMethod(LinkMovementMethod.getInstance());

				builder.setView(dialoglayout);
				return builder.create();
			}
		
		}
		
		return null;
	}
}